package com.thinkit.bigdata.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.thinkit.bigdata.core.entity.ResultMsg;
import com.thinkit.bigdata.core.feature.orm.mybatis.Page;
import com.thinkit.bigdata.core.util.PropertiesUtil;
import com.thinkit.bigdata.web.model.bus.*;
import com.thinkit.bigdata.web.model.config.SysArea;
import com.thinkit.bigdata.web.model.config.SysAreaExample;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.service.bus.BusModelRuleService;
import com.thinkit.bigdata.web.service.bus.BusModelService;
import com.thinkit.bigdata.web.service.bus.BusModelTypeService;
import com.thinkit.bigdata.web.service.bus.BusWorkModelService;
import com.thinkit.bigdata.web.service.config.AreaService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Create by lichangyuan 2018年9月25日
 * 包含了bus_model（模型信息）和bus_model_type（模型分类信息）的相关增删改查，
 * 其中有部分涉及到权限操作的（比如当前访问用户的是否操作数据的权限，可能需要仔细推敲一下）。
 * 绝大部分接口的返回结果使用内部类 {@link ResultBean}去封装查询结果。
 * modify by lichangyuan 2018年9月27日
 */
@Controller
@Scope("prototype")
@RequestMapping("model")
public class ModelManagementController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ModelManagementController.class);

    @Autowired
    private BusWorkModelService workModelService;

    @Autowired
    private BusModelService busModelService;

    @Autowired
    private BusModelTypeService busModelTypeService;

    @Autowired
    private BusModelRuleService busModelRuleService;

    @Autowired
    private AreaService areaService;

    private static ObjectMapper mapper = new ObjectMapper();
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private ResultBean resultBean = new ResultBean();

    private static final Integer ERROR_CODE_DEFAULT = -9999;
    private static final String ERROR_MSG_DEFAULT = "出现异常！";

    private static final Integer SUCCESS_CODE_DEFAULT = 0;
    private static final String SUCCESS_MSG_DEFAULT = "操作成功";


    private static final String ERROR_MSG_IDENTIFY = "您没有操作该数据的权限！";
    private static final String USER_INFO = "【当前请求用户信息】：";
    private static final String USER_AREA = "【当前请求用户所属地区编码】：";
    private static final String USER_IDENTITY = "【当前请求用户身份】：";


    private String provincecode;
    private Integer provinceid;
    private Long groupid;
    private Integer identity;
    private User user = null;
    private Long userid = null;
    private Boolean userstatus = false;
    private Boolean permission = false;
    /**
     * 是否集团人员
     */
    private Boolean admin = false;

    /**
     * 目前用户身份判断逻辑不是很完善，后续可能需要优化
     * <p>没有所属机构的人为超管（身份标识为2 数据权限标识userIds不设置 其他地方取值的时候为null</p>
     * <p>// 有所属机构的人员不是超管人员 判断并保存人员身份标识（坐席0，质检员1  其他2）</p>
     */
    @ModelAttribute
    public void beforeMethod() {
        try {
            LOGGER.info("判断用户身份！");
            User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
            //是否登陆
            if (user == null) {
                this.user = null;
                this.userid = null;
                LOGGER.info(USER_IDENTITY + "未登录！");
                return;
            } else {
                this.user = user;
                this.userid = user.getId();
            }
            LOGGER.info(USER_INFO + mapper.writeValueAsString(user));
            SysArea areaInfo = (SysArea) SecurityUtils.getSubject().getSession().getAttribute("areaInfo");
            if(areaInfo == null ||areaInfo.getId() == null){
                LOGGER.info(USER_IDENTITY + "是集团人员");
                //集团人员
                this.admin = true;
                this.provincecode = null;
            }else{
                LOGGER.info(USER_IDENTITY + "是省份人员");
                this.admin = false;
                this.provincecode = areaInfo.getCode();
            }
        } catch (Exception e) {
            LOGGER.error("获取当前请求用户信息异常！", e);
            return;
        }
    }

    /**
     * 查询模型任务状态
     *
     * @param body
     * @return
     */
    @ResponseBody
    @RequestMapping("query_model_task_status")
    public ResultBean query_model_task_status(@RequestBody Map<String, Object> body) {
        if(body==null||body.get("ids")==null){
            return new ResultBean(-9999, "参数异常!");
        }
        try {
            List<Long> ids = (List<Long>) body.get("ids");
            List<Map<String, Object>> maps = busModelService.query_modelTask_status(ids);
            return new ResultBean(0, "查询成功", maps);
        } catch (Exception e) {
            LOGGER.error("数据库异常,打印异常信息{}", e);
            return new ResultBean(-9999, "数据库异常");
        }
    }

    /**
     * 检测: 规则下线时使用的模型是否已上线
     *
     * @param body
     * @return
     */
    @ResponseBody
    @RequestMapping("query_model_status")
    public Object query_model_status(@RequestBody Map<String, Object> body) {
        LOGGER.info("规则下线检测模型状态接口入参:{}\n" + body.toString());
        if(body==null||body.get("ruleIds")==null){
            HashMap<String, Object> result = new HashMap<>(2);
            result.put("rtnCode", "-9999");
            result.put("rtnMsg", "接口入参为空");
            return result;
        }
        List<Object> pmList = (List<Object>) body.get("ruleIds");
        List<Long> ruleIds = new ArrayList<>();
        for(Object o:pmList){
            try{
                ruleIds.add(Long.parseLong(o.toString()));
            }catch (Exception e){
                //防止参数为字符串
            }
        }
        if (ruleIds.size() < 1) {
            HashMap<String, Object> result = new HashMap<>(2);
            result.put("rtnCode", "-8888");
            result.put("rtnMsg", "接口入参ruleIds不符合要求");
            return result;
        }
        try {
            //查询模型任务状态
            List<Object> result_list = busModelService.query_model_status(ruleIds);
            return result_list;
        } catch (Exception e) {
            HashMap<String, Object> result = new HashMap<>(2);
            result.put("rtnCode", "-1111");
            result.put("rtnMsg", "数据库异常");
            return result;
        }
    }

    /**
     * 更新规则名称: 同时更新所有规则名称
     *
     * @param params 参数需要包含rules
     * @return
     */
    @ResponseBody
    @RequestMapping("update_offline_model_rule")
    public ResultMsg update_offline_model_rule(@RequestBody Map<String, Object> params) {
        String pmName = "rules";
        LOGGER.info("规则名称更新接口入参:{}", params);
        if (params ==null || params.size() < 1 ||params.get(pmName)==null) {
            return ResultMsg.errorResult(-9998,"接口入参为空");
        }
        List<Map<String, Object>> rules;
        try{
            rules = (List<Map<String, Object>>) params.get(pmName);
        } catch (Exception e) {
            LOGGER.error("参数异常", e);
            return ResultMsg.errorResult("数据库异常");
        }
        try {
            for(Map<String, Object> map:rules){
                if(map.get("id")==null||map.get("name")==null){
                    return ResultMsg.errorResult(-9997,"接口入参为不正确");
                }else{
                    Long ruleId = Long.parseLong(map.get("id").toString());
                    String ruleName = map.get("name").toString();
                    BusModelRuleExample example = new BusModelRuleExample();
                    example.createCriteria().andRuleidEqualTo(ruleId);
                    BusModelRule busModelRule = new BusModelRule();
                    busModelRule.setRulename(ruleName);
                    busModelRuleService.updateByExampleSelective(busModelRule,example);
                }
            }
            return ResultMsg.successResult();
        } catch (Exception e) {
            LOGGER.error("数据库异常,打印异常信息{}", e);
            return ResultMsg.errorResult("数据库异常");
        }
    }

    /**
     * 删除本地规则: 删除规则同时删除模型关系,用于删除未上线的模型关系
     *
     * @param body ,
     * @return
     */
    @ResponseBody
    @RequestMapping("delete_offline_model_rule")
    public ResultMsg delete_offline_model_rule(@RequestBody Map<String, Object> body) {
        LOGGER.info("规则删除检测模型状态接口入参:{}", body);
        if(body == null || body.get("ruleIds")==null){
            return ResultMsg.errorResult(-9998,"接口参数为空");
        }
        List<Long> ruleIds = (List<Long>) body.get("ruleIds");
        if (ruleIds.size() < 1) {
            return ResultMsg.errorResult(-9998,"接口入参ruleIds为空");
        }
        try {
            busModelRuleService.delete_offline_model_rule(ruleIds);
            return ResultMsg.successResult("成功");
        } catch (Exception e) {
            LOGGER.error("数据库异常,打印异常信息{}", e);
            return ResultMsg.errorResult("数据库异常");
        }
    }

    /**
     * 插入模型分类 OK
     * <p>
     * 根据当前访问的用户id、省份信息，插入模型分类信息
     *
     * @param parentid 父节点
     * @param name     添加节点的名字
     * @return {@link ResultBean}，封装了更新后的模型分类列表{@link List<BusModelType> modelTypeList} 对象
     */
    @ResponseBody
    @RequestMapping("insert/modelTypeByExample")
    public synchronized ResultBean add_model_type(
            @RequestParam(value = "parentid", required = false) Long parentid,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "provincecode") String provincecode,
            @RequestParam(value = "note", required = false) String note
    ) {
        try {
            LOGGER.info("插入模型分类！");
            if (StringUtils.isBlank(provincecode)) {
                return new ResultBean(ERROR_CODE_DEFAULT, "省份信息输入错误！", null);
            } else if (this.admin == false && !provincecode.equals(this.provincecode)) {
                return new ResultBean(ERROR_CODE_DEFAULT, "不是本地区用户禁止添加数据！");
            } else if (StringUtils.isEmpty(name)) {
                return new ResultBean(ERROR_CODE_DEFAULT, "名称不能为空");
            }
            //当直接在省份下 添加的时候不能加判断
            if (parentid != null) {
                BusModelExample example1 = new BusModelExample();
                example1.createCriteria()
                        .andTypeidEqualTo(parentid);
                List<BusModel> busModels = busModelService.selectByExample(example1);
                if (!busModels.isEmpty()) {
                    return new ResultBean(ERROR_CODE_DEFAULT, "数据节点下不能创建分类节点");
                }
            }
            // 判断用户状态和权限
            //查询该省份下模型分类名字是否重复
            BusModelTypeExample example = new BusModelTypeExample();
            BusModelTypeExample.Criteria c = example.createCriteria();

            c.andProvincecodeEqualTo(provincecode).andNameEqualTo(name);
            if (parentid != null) {
                c.andParentidEqualTo(parentid);
            } else {
                c.andParentidIsNull();
            }
            List<BusModelType> busModelTypeList = busModelTypeService.selectByExample(example);
            //插入模型分类
            if (!busModelTypeList.isEmpty()) {
                return new ResultBean(-9998, "模型分类重复");
            } else {
                BusModelType busModelType = new BusModelType();
                busModelType.setId(null);
                //父ID可以时null
                busModelType.setParentid(parentid);
                busModelType.setName(name);
                busModelType.setCreatetime(new Date());
                busModelType.setCreateuserid(this.userid);
                //0 不是叶子,1 是叶子 ,叶子节点可以有模型和分类, 非叶子节点,只能有分类, 默认都是叶子节点. 如果先插入模型, leaf=1,先插入分类,leaf=0
                busModelType.setLeaf(0);
                busModelType.setProvincecode(provincecode);
                busModelType.setNote(note);
                busModelTypeService.insertSelective(busModelType);
                return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT, null, busModelType);
            }
        } catch (Exception e) {
            LOGGER.error("插入模型分类出现异常！", e);
            return resultBean;
        }
    }

    private boolean deleteModeByModelExample(BusModelExample modelExample){
        List<BusModel> list = busModelService.selectByExample(modelExample);
        List<Long> modelIds = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (BusModel model : list) {
                modelIds.add(model.getId());
            }
            busModelService.deleteByExample(modelExample, modelIds);
        }
        return true;
    }

    /**
     * 删除模型分类，同时需要删除该模型分类下的所有模型数据
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete/modelTypeByExample")
    public ResultBean delete_model_type(
            @RequestParam(value = "ids") Long id
    ) {
        try {
            LOGGER.info("删除模型分类！");
            if (id < 0) {
                //删除所有分类
                int areaId = (int) -id;
                SysArea area = areaService.selectByPrimaryKey(areaId);
                //删除所有分类
                BusModelTypeExample example = new BusModelTypeExample();
                example.createCriteria()
                        .andProvincecodeEqualTo(area.getCode());
                busModelTypeService.deleteByExample(example);

                //删除模型
                BusModelExample modelExample = new BusModelExample();
                modelExample.createCriteria().andProvincecodeEqualTo(area.getCode());
                deleteModeByModelExample(modelExample);
                return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT);
            } else {
                //查询子分类
                List<Long> typeIds = formatTypeIds(id);
                //删除分类
                BusModelTypeExample example = new BusModelTypeExample();
                example.createCriteria().andIdIn(typeIds);
                busModelTypeService.deleteByExample(example);
                //删除分类下的模型
                BusModelExample modelExample = new BusModelExample();
                modelExample.createCriteria().andTypeidIn(typeIds);
                deleteModeByModelExample(modelExample);
                return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT);
            }

        } catch (Exception e) {
            LOGGER.error("删除模型分类出现异常！", e);
            return resultBean;
        }
    }

    /**
     * 删除模型分类前校验，校验是否可以删除 ，是否需要提示删除，是否不能删除
     * 2为不可删除， 1为可以有特殊数据删除注意提示  0，可以直接删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("checkDelete/modelTypeByExample")
    public ResultBean check_model_type_allow_delete(
            @RequestParam(value = "ids") Long id
    ) {
        try {
            LOGGER.info("删除模型分类前校验！");
            List<BusModel> modelList;
            String nodeText;
            if (id < 0) {
                nodeText = "省份";
                int areaId = (int) -id;
                SysArea area = areaService.selectByPrimaryKey(areaId);
                //删除前检查模型是否使用，是否已上线
                BusModelExample modelExample = new BusModelExample();
                modelExample.createCriteria().andProvincecodeEqualTo(area.getCode());
                modelList = busModelService.selectByExample(modelExample);
            } else {
                nodeText = "分类";
                //查询子分类
                List<Long> typeIds = formatTypeIds(id);
                //删除分类下的模型
                BusModelExample modelExample = new BusModelExample();
                modelExample.createCriteria().andTypeidIn(typeIds);
                modelList = busModelService.selectByExample(modelExample);
            }
            if (modelList != null && modelList.size() > 0) {
                List<Long> modelIds = new ArrayList<>();
                List<Long> postModelIds = new ArrayList<>();
                for (BusModel model : modelList) {
                    if (model.getPoststatus() == 1) {
                        postModelIds.add(model.getId());
                    }
                    modelIds.add(model.getId());
                }
                BusWorkModelExample workModelExample = new BusWorkModelExample();
                workModelExample.createCriteria().andModelidIn(modelIds);
                List<BusWorkModel> workModels = workModelService.selectByExample(workModelExample);
                if (workModels != null && workModels.size() > 0) {
                    return new ResultBean(2, "所选" + nodeText + "下已有模型被添加到任务中，不能删除");
                }
                if (postModelIds.size() > 0) {
                    return new ResultBean(2, "所选" + nodeText + "下存在已上线的数据，不能删除");
                }
                return new ResultBean(1, "所选" + nodeText + "下存在模型数据，删除将会删除所有已存在模型数据");
            } else {
                return new ResultBean(SUCCESS_CODE_DEFAULT, "可以删除");
            }
        } catch (Exception e) {
            LOGGER.error("删除模型分类校验出现异常！", e);
            return new ResultBean(-1, "系统异常");
        }
    }

    /**
     * 修改模型分类节点信息
     * 根据当前访问的用户userid、省份信息(provincecode)，更新模型分类信息
     * 先根据id查询模型分类信息，然后根据省份编码和模型创建人，判断是否用权限更新模型分类信息
     *
     * @param id   被修改节点的id
     * @param name 修改后节点名
     * @return {@link ResultBean}，封装了{@link List<BusModelType> modelTypeList} 对象
     */
    @ResponseBody
    @RequestMapping("update/modelTypeByExample")
    public ResultBean update_model_type(
            @RequestParam(value = "parentid", required = false) Long parentid,
            @RequestParam(value = "id") Long id,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "note", required = false) String note
    ) {
        try {
            LOGGER.info("更新模型分类！");
            //组装模型分类信息
            if (id == null){
                return new ResultBean(ERROR_CODE_DEFAULT, "模型分类id不能是空");
            }
            if (StringUtils.isBlank(name)){
                return new ResultBean(ERROR_CODE_DEFAULT, "模型分类name不能是空");
            }
            //查询旧的模型分类信息
            BusModelType record = busModelTypeService.selectByPrimaryKey(id);
            BusModelTypeExample example = new BusModelTypeExample();
            BusModelTypeExample.Criteria c = example.createCriteria();
            //在一个省份下同层下不能存在相同的模型分类名称
            c.andProvincecodeEqualTo(record.getProvincecode())
                    .andIdNotEqualTo(id).andNameEqualTo(name);
            if(parentid != null && parentid>0){
                c.andParentidEqualTo(parentid);
            }else if (parentid == null||parentid <0||record.getParentid() == null) {
                c.andParentidIsNull();
            } else {
                c.andParentidEqualTo(record.getParentid());
            }
            List<BusModelType> list = busModelTypeService.selectByExample(example);
            if (list != null && list.size() > 0) {
                //存在同名的
                return new ResultBean(-9998, "模型分类重复！");
            } else {
                record.setName(name);
                record.setNote(note);
                record.setParentid(parentid);
                int i = busModelTypeService.updateByPrimaryKey(record);
                if (i == 0) {
                    return new ResultBean(-9999, "系统保存异常");
                } else {
                    return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT);
                }
            }

        } catch (Exception e) {
            LOGGER.error("更新模型分类出现异常！", e);
            return resultBean;
        }
    }

    /**
     * 判断模型类别能添加什么数据（0所有都可以添加，1只能添加模型分类，2只能添加模型，-1系统异常，都不可以添加）
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("checkData/modelTypeByExample")
    public ResultBean check_model_type_allow_data(
            @RequestParam(value = "id") Long id
    ) {
        LOGGER.info("检查指定模型分类下能添加分类还是模型！");
        if (id < 0) {
            return new ResultBean(1, "只能添加分类");
        } else {
            try {
                BusModelTypeExample example = new BusModelTypeExample();
                BusModelTypeExample.Criteria c = example.createCriteria();
                //在一个省份下同层下不能存在相同的模型分类名称
                c.andParentidEqualTo(id);
                List<BusModelType> list = busModelTypeService.selectByExample(example);
                if (list != null && list.size() > 0) {
                    return new ResultBean(1, "只能添加分类");
                }
                BusModelExample example1 = new BusModelExample();
                example1.createCriteria().andTypeidEqualTo(id);
                List<BusModel> list1 = busModelService.selectByExample(example1);
                if (list1 != null && list1.size() > 0) {
                    return new ResultBean(2, "只能添加模型");
                }
                return new ResultBean(0, "模型和模型分类都可以添加");
            } catch (Exception e) {
                LOGGER.error("系统异常！", e);
                return new ResultBean(-1, "系统异常，不能添加任何数据");
            }
        }
    }

    /**
     * 判断添加或修改的类型是否唯一，其中当添加判断时不传id，修改时传值id
     *
     * @param id           添加时不传，修改时传值
     * @param name
     * @param provincecode
     * @return
     */
    @ResponseBody
    @RequestMapping("checkOnly/modelTypeByExample")
    public ResultBean check_model_type_unique(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "provincecode") String provincecode,
            HttpServletRequest request
    ) {
        try {
            LOGGER.info("判断添加或修改的模型分类名称是否已存在");
            BusModelTypeExample example = new BusModelTypeExample();
            BusModelTypeExample.Criteria c = example.createCriteria();
            c.andNameEqualTo(name).andProvincecodeEqualTo(provincecode);
            String parentid = request.getParameter("parentid");
            if (Strings.isNullOrEmpty(parentid) || Long.parseLong(parentid) < 0) {
                c.andParentidIsNull();
            } else {
                c.andParentidEqualTo(Long.parseLong(parentid));
            }
            if (id != null) {
                c.andIdNotEqualTo(id);
            }
            List<BusModelType> list = busModelTypeService.selectByExample(example);
            if (list != null && list.size() > 0) {
                return new ResultBean(-9999, "模型分类名称已经存在");
            } else {
                return new ResultBean(0, "");
            }
        } catch (Exception e) {
            LOGGER.error("系统异常！", e);
            return new ResultBean(-1, "系统异常");
        }
    }


    /**
     * 查询模型分类信息，生成jstree对象
     * <p>
     * 默认根据当前用户所在的省份信息(provincecode),查询模型分类。
     *
     * @return {@link ResultBean}，封装了{@link JsTreeNode} 对象
     */
    @ResponseBody
    @RequestMapping("select/modelTypeTree")
    public ResultBean build_model_type_tree(@RequestParam(value = "provinceCode", required = false) String provinceCode) {
        try {
            LOGGER.info("查询模型分类树！");
//            生成jstree
            JsTreeNode node = buildModelTypeTree(new JsTreeNode(),provinceCode);
            LOGGER.info(mapper.writeValueAsString(node));
            return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT, null, node);
        } catch (Exception e) {
            LOGGER.error("查询模型分类出现异常！", e);
            return resultBean;
        }
    }

    /**
     * 查询模型分类信息
     * <p>
     * 默认根据当前用户所在的省份信息(provincecode),查询模型分类。
     *
     * @return {@link ResultBean}，封装了{@link List<BusModel> modelTypeList} 对象
     */
    @ResponseBody
    @RequestMapping("select/modelTypeByExample")
    public ResultBean query_model_type(
            @RequestParam(value = "provincecode", required = true) String provincecode,
            @RequestParam(value = "selfId", required = false) Long selfId
    ) {

        try {
            LOGGER.info("查询模型分类！");
            // 判断用户状态和权限,查询模型分类必须输入省份
//            if (StringUtils.isBlank(provincecode)) return new ResultBean(ERROR_CODE_DEFAULT, "省份信息不能为空!");
//            SysArea area = (SysArea) SecurityUtils.getSubject().getSession().getAttribute("areaInfo");
            BusModelTypeExample example = new BusModelTypeExample();
            BusModelTypeExample.Criteria criteria = example.createCriteria();
            if(selfId != null){
                criteria.andIdNotEqualTo(selfId);
            }
            if (this.admin == false) {
                //组装查询条件
                criteria.andProvincecodeEqualTo(this.provincecode);
                List<BusModelType> modelTypeList = busModelTypeService.selectByExample(example);
                return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT, modelTypeList.size(), modelTypeList);
            } else {
                if (!(provincecode.equals("") || provincecode == null)) {
                    criteria.andProvincecodeEqualTo(provincecode);
                }
                List<BusModelType> modelTypeList = busModelTypeService.selectByExample(example);
                return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT, modelTypeList.size(), modelTypeList);
            }

        } catch (Exception e) {
            LOGGER.error("查询模型分类出现异常！", e);
            return resultBean;
        }
    }


    /**
     * 检查模型名称是否已经存在，目前是同类型下判断，需要传值
     * id、name、provincecode、typeid
     * 其中id 添加时不传，修改时传值
     *
     * @param busModel {@link BusModel}
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkOnly/modelByExample")
    public ResultBean check_model_name_unique(@RequestBody BusModel busModel) {
        try {
            LOGGER.info("添加模型前判断模型名称是否已经存在");
            // 省份信息不能是空
            if (StringUtils.isBlank(busModel.getProvincecode())) {
                return new ResultBean(ERROR_CODE_DEFAULT, "省份信息输入错误！", null);
            } else if (this.admin == false && !busModel.getProvincecode().equals(this.provincecode)) {
                return new ResultBean(ERROR_CODE_DEFAULT, "不是本地区用户禁止添加数据！");
            }
            // 模型名称不能是空
            if (StringUtils.isBlank(busModel.getName())) {
                return new ResultBean(ERROR_CODE_DEFAULT, "模型名称不能为空！", null);
            }
            BusModelExample example = new BusModelExample();
            BusModelExample.Criteria c = example.createCriteria();
            c.andTypeidEqualTo(busModel.getTypeid()).andNameEqualTo(busModel.getName());
            if (busModel.getId() != null) {
                c.andIdNotEqualTo(busModel.getId());
            }

            List<BusModel> list = busModelService.selectByExample(example);
            if (list != null && list.size() > 0) {
                return new ResultBean(-9999, "模型名称已经存在");
            } else {
                return new ResultBean(0, "");
            }
        } catch (Exception e) {
            LOGGER.error("系统出现异常！", e);
            return new ResultBean(-1, "系统异常");
        }
    }

    /**
     * 插入一条模型信息
     * <p>
     * 插入模型必须要传递，模型名称(name)、模型分类(typeid)、省份(provincecode)、规则列表(modelrulelist)、分数(fullscore)缺省值100,
     * 非必需参数 创建时间(createtime)、创建人(createuserid)、更新时间（lastupdatetime）、最后更新人(lastupdateuserid)、上线状态(poststatus)、上线时间(onsettime)
     *
     * <p>业务描述:</p>
     * <p> 必填省份,分类</p>
     * <p> 非必填省份,规则</p>
     *
     * @param busModel {@link BusModel}
     * @return
     */
    @ResponseBody
    @RequestMapping("/insert/modelByExample")
    public synchronized ResultBean add_model(@RequestBody BusModel busModel) {
        try {
            LOGGER.info("插入模型！" + mapper.writeValueAsString(busModel));
            // 省份信息不能是空
            if (StringUtils.isBlank(busModel.getProvincecode())) {
                return new ResultBean(ERROR_CODE_DEFAULT, "省份信息不能为空！", null);
            } else if (this.admin == false && !busModel.getProvincecode().equals(this.provincecode)) {
                return new ResultBean(ERROR_CODE_DEFAULT, "禁止添加非本省数据！");
            }
            // 模型名称不能是空
            if (StringUtils.isBlank(busModel.getName())){
                return new ResultBean(ERROR_CODE_DEFAULT, "模型名称不能为空！", null);
            }
            BusModelTypeExample example = new BusModelTypeExample();
            example.createCriteria().andParentidEqualTo(busModel.getTypeid());
            List<BusModelType> busModelTypes = busModelTypeService.selectByExample(example);
            if (!busModelTypes.isEmpty()){
                return new ResultBean(ERROR_CODE_DEFAULT, "不能在分类节点添加数据!");
            }
            BusModelExample modelExample = new BusModelExample();
            modelExample.createCriteria().andNameEqualTo(busModel.getName())
                    .andTypeidEqualTo(busModel.getTypeid());
            List<BusModel> checkList = busModelService.selectByExample(modelExample);
            if(checkList!=null&&checkList.size()>0){
                return new ResultBean(ERROR_CODE_DEFAULT, "不能在同分类下添加同名模型!");
            }
            //组装模型信息
            Date date = new Date();
            busModel.setCreatetime(date);
            busModel.setLastupdatetime(date);
            busModel.setTesttimes(0);
            busModel.setPoststatus(0);
            busModel.setCreateuserid(this.userid);
            busModel.setLastupdateuserid(this.userid);
            if (busModel.getFullscore() == null) {
                busModel.setFullscore(100);
            }
            int i = busModelService.insert(busModel);
            return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT, i, busModel);
        } catch (Exception e) {
            LOGGER.error("插入模型出现异常！", e);
            return resultBean;
        }
    }

    /**
     * 更新模型数据
     * <p>
     * 根据模型id，更新模型。和更新模型分类不同的是，这里直接是在sql中加删除条件，如果用户符合模型所属省份和模型创建人，则更新。
     *
     * @param busModel {@link BusModel}
     * @return 使用自定义的实体类{@link ResultBean}
     */
    @ResponseBody
    @RequestMapping("update/modelByExampleSelective")
    public ResultBean update_model(@RequestBody BusModel busModel) {
        try {
            LOGGER.info("更新模型！");
            //先判断模型是否是下线状态，是 可以修改。
            if (busModel.getPoststatus() != null && busModel.getPoststatus() != 0){
                return new ResultBean(ERROR_CODE_DEFAULT, "上线的模型不可以修改！");
            }
            // 判断省份信息是否存在，封装模型数据。
            if (StringUtils.isBlank(busModel.getProvincecode())){
                return new ResultBean(ERROR_CODE_DEFAULT, "省份信息输入错误！");
            }
            BusModelExample modelExample = new BusModelExample();
            modelExample.createCriteria().andNameEqualTo(busModel.getName())
                    .andTypeidEqualTo(busModel.getTypeid())
                    .andIdNotEqualTo(busModel.getId());
            List<BusModel> checkList = busModelService.selectByExample(modelExample);
            if(checkList!=null&&checkList.size()>0){
                return new ResultBean(ERROR_CODE_DEFAULT, "同分类下已经存在相同名称的模型!");
            }
            // 组装模型信息
            busModel.setLastupdateuserid(this.userid);
            busModel.setLastupdatetime(new Date());
            //不允许修改模型所属省份。
            busModel.setProvincecode(null);
            int i = busModelService.updateByPrimaryKeySelective(busModel);
            return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT);
        } catch (Exception e) {
            LOGGER.error("更新模型出现异常！", e);
            return resultBean;
        }
    }


    /**
     * 删除模型
     * <p>
     * 根据模型id、创建模型用户createuserid、登陆用户所属省份信息provincecode,删除模型.如果删除有失败的模型，返回{@link #ERROR_CODE_DEFAULT}和未删除模型信息
     *
     * @param ids id数组
     * @return 使用自定义的实体类{@link ResultBean}
     */
    @ResponseBody
    @RequestMapping("/delete/modelByExample")
    public ResultBean delete_model(@RequestParam(value = "ids", required = true) Long[] ids) {
        LOGGER.info("删除模型！");
        String msg = "";
        int pass = 0;
        int fail = 0;
        try {
            //判断数组内容是否是null
            if (ArrayUtils.isEmpty(ids)) return resultBean;
            LOGGER.info("删除数据" + Arrays.toString(ids));
            List<Long> idlist = Arrays.asList(ids);
            // 判断用户状态和权限

            //组装查询条件
            BusModelExample example = new BusModelExample();
            example.createCriteria()
                    .andIdIn(idlist);
            List<BusModel> busModels = busModelService.selectByExample(example);
            //开始删除模型
            for (BusModel record : busModels) {
//                if (this.admin == true || record.getCreateuserid().equals(this.userid)) {
                    if (record.getPoststatus() == 0) {
                        int i = busModelService.deleteByPrimaryKey(record.getId());
                        pass++;
                    } else {
                        msg += record.getName() + "模型需要下线才能删除!<br>";
                        fail++;
                    }
//                } else {
//                    msg += record.getName() + "没有操作权限!<br>";
//                    fail++;
//                }
            }
            // 如果不是集团人员，添加省份判断条件
            // criteria 查询条件为null，会报运行时异常。
            if (fail == ids.length) {
                return new ResultBean(ERROR_CODE_DEFAULT, msg);
            } else {
                return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT + msg, fail, null);
            }
        } catch (Exception e) {
            LOGGER.error("删除模型出现异常！", e);
            return resultBean;
        }
    }

    /**
     * 删除模型前校验，校验是否可以删除 ，是否需要提示删除，是否不能删除
     * 2为不可删除， 0可以直接删除 ,-1系统异常，不再做任何操作
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("checkDelete/modelByExample")
    public ResultBean check_model_allow_delete(
            @RequestParam(value = "ids") List<Long> ids
    ) {
        try {
            LOGGER.info("删除模型前校验！");
            //删除分类下的模型
            BusWorkModelExample workModelExample = new BusWorkModelExample();
            workModelExample.createCriteria().andModelidIn(ids);
            List<BusWorkModel> workModels = workModelService.selectByExample(workModelExample);
            if (workModels != null && workModels.size() > 0) {
                return new ResultBean(2, "所选模型已有模型被添加到任务中，不能被删除");
            }
            return new ResultBean(SUCCESS_CODE_DEFAULT, "所选模型可以被删除");
        } catch (Exception e) {
            LOGGER.error("删除模型校验出现异常！", e);
            return new ResultBean(-1, "系统异常");
        }
    }

    /**
     * 分页查询模型信息
     * <p>
     * 目前模型上线状态功能需要完善  2018年9月26日22点36分
     *
     * @param limit        页面尺寸
     * @param offset       偏移量
     * @param classify     模型分类
     * @param provincecode 省份编码
     * @param person       模型创建人
     * @param modelname    模型名称
     * @param keyinclude   关键字
     * @param state        状态
     * @param start        起始时间
     * @param end          结束时间
     * @return {@link ResultBean} 装载分页条件查询结果  count(总条目数) data(数据集合) code(结果码) msg(描述信息)
     */
    @ResponseBody
    @RequestMapping("/select/byMutiConditionAndPagenationAndMutilTable")
    public ResultBean query_model_pagination(
            @RequestParam(value = "sortName", required = false) String sortName,
            @RequestParam(value = "sortOrder", required = false) String sortOrder,
            @RequestParam(value = "limit", required = true, defaultValue = "20") Integer limit,
            @RequestParam(value = "offset", required = true, defaultValue = "0") Integer offset,
            @RequestParam(value = "classify", required = true) String classify,
            @RequestParam(value = "provincecode", required = true) String provincecode,
            @RequestParam(value = "person", required = true) String person,
            @RequestParam(value = "modelname", required = true) String modelname,
            @RequestParam(value = "keyinclude", required = true) String keyinclude,
            @RequestParam(value = "state", required = true) String state,
            @RequestParam(value = "start", required = true) Date start,
            @RequestParam(value = "end", required = true) Date end
    ) {
        LOGGER.info("查询模型!");
        LOGGER.info("分页尺寸：" + limit);
        LOGGER.info("偏移量：" + offset);
        LOGGER.info("省份：" + provincecode);
        LOGGER.info("模型分类：" + classify);
        LOGGER.info("创建人：" + person);
        LOGGER.info("模型名称:" + modelname);
        LOGGER.info("关键字：" + keyinclude);
        LOGGER.info("模型状态：" + state);
        LOGGER.info("起始时间：" + start);
        LOGGER.info("结束时间：" + end);
        try {

            // 封装查询条件
            HashMap<String, Object> params = new HashMap<>();
            // 不是集团人员，只能查当前省份
            if (!this.admin) {
                provincecode = this.provincecode;
            }
            params.put("provincecode", provincecode);
            params.put("typeids", classify);
            params.put("createuserid", person);
            params.put("name", modelname);
            params.put("note", keyinclude);
            params.put("poststatus", state);
            params.put("startdate", start);
            params.put("enddate", end);
            if (StringUtils.isNotEmpty(sortName)) {
                if("userName".equalsIgnoreCase(sortName)){
                    params.put("sortName", sortName);
                }else if("modeltypename".equalsIgnoreCase(sortName)){
                    params.put("sortName", "tname");
                }else if("areaname".equalsIgnoreCase(sortName)){
                    params.put("sortName", "area");
                }else{
                    params.put("sortName", "m."+sortName);
                }
                if (StringUtils.isNotEmpty(sortOrder)
                    &&("DESC".equalsIgnoreCase(sortOrder)||"ASC".equalsIgnoreCase(sortOrder))) {
                    params.put("sortOrder", sortOrder);
                }
            }
            if (StringUtils.isNotEmpty(classify)) {
                params.put("typeids", formatTypeIds(Long.parseLong(classify)));
            }
            // 查询模型表、模型分类表、地区表、用户表、规则列表 4表联查和一对多查询。
            Page<BusModel> page = new Page<>((offset / limit) + 1, limit);
            List<BusModel> busModelList = busModelService.selectByPage(page, params);
            return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT, page.getTotalCount(), busModelList);
        } catch (Exception e) {
            LOGGER.error("查询模型出现异常！", e);
            return resultBean;
        }
    }

    /**
     * 模型上线
     *
     * @param ids 模型id
     * @return {@link ResultBean}
     */
    @ResponseBody
    @RequestMapping("/online/model")
    public ResultBean model_online(@RequestParam(value = "ids", required = true) Long[] ids) {
        LOGGER.info("模型上线！");
        String msg = "";
        int pass = 0;
        int fail = 0;
        try {
            // 判断id数组长度是否是空
            if (ArrayUtils.isEmpty(ids)) return new ResultBean(SUCCESS_CODE_DEFAULT, "id不能空!");
            List<Long> idList = Arrays.asList(ids);
            // 判断用户状态和权限
            //组装模型查询条件
            BusModelExample example = new BusModelExample();
            example.createCriteria()
                    .andIdIn(idList)
                    .andPoststatusEqualTo(0);
            List<BusModel> busModels = busModelService.selectByExample(example);
            for (BusModel record : busModels) {
//                if (this.admin == true || record.getCreateuserid().equals(this.userid)) {
                    record.setPoststatus(1);
                    record.setOnsettime(new Date());
                    record.setLastupdatetime(new Date());
                    int i = busModelService.updateByPrimaryKey(record);
                    pass++;
                    msg += record.getName() + "上线成功!<br>";
//                } else {
//                    msg += record.getName() + "没有操作权限!<br>";
//                    fail++;
//                }
            }
            // 设置Poststatus 为1 已上线，默认是0 未上线。
            // 上线模型
            if (fail == ids.length) {
                return new ResultBean(ERROR_CODE_DEFAULT, msg);
            } else {
                return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT);
            }
        } catch (Exception e) {
            LOGGER.error("模型上线出现异常！" + msg, e);
            return new ResultBean(ERROR_CODE_DEFAULT, "模型上线出现异常！" + msg);
        }

    }

    /**
     * 模型下线
     *
     * @param ids 下线模型的id
     * @return {@link ResultBean}
     */
    @ResponseBody
    @RequestMapping("/offline/model")
    public ResultBean model_offline(@RequestParam(value = "ids", required = true) Long[] ids) {
        LOGGER.info("模型下线:id=" + ids.toString());
        String msg = "";
        int pass = 0;
        int fail = 0;
        try {
            if (ArrayUtils.isEmpty(ids)) return resultBean;
            List<Long> idList = Arrays.asList(ids);
            //组装模型查询条件
            BusModelExample example = new BusModelExample();
            example.createCriteria()
                    .andIdIn(idList)
                    .andPoststatusEqualTo(1);
            List<BusModel> busModels = busModelService.selectByExample(example);
            //模型下线
            for (BusModel record : busModels) {
//                if (this.admin == true || record.getCreateuserid().equals(this.userid)) {
                    record.setPoststatus(0);
//                    record.setOnsettime(null);
                    record.setLastupdatetime(new Date());
                    int i = busModelService.updateByPrimaryKey(record);
                    pass++;
                    msg += record.getName() + "下线成功!<br>";
//                } else {
//                    msg += record.getName() + "没有操作权限!<br>";
//                    fail++;
//                }
            }
            if (fail == ids.length) {
                return new ResultBean(ERROR_CODE_DEFAULT, msg);
            } else {
                return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT, pass, null);
            }
        } catch (Exception e) {
            LOGGER.error("模型下线出现异常！", e);
            return new ResultBean(ERROR_CODE_DEFAULT, "模型下线出现异常！<br>" + msg, pass);
        }
    }

    /**
     * 复制模型
     * <p>
     * 复制后的模型是，下线状态、其余信息根据用户信息修改
     *
     * @param ids 复制模型的id
     * @return
     */
    @ResponseBody
    @RequestMapping("/copy/model")
    public ResultBean model_copy(@RequestParam(value = "ids", required = true) Long[] ids) {
        LOGGER.info("模型复制:id=" + ids.toString());
        try {
            if (ArrayUtils.isEmpty(ids)) return resultBean;
            List<Long> idList = Arrays.asList(ids);
            // 判断用户状态和权限
            //组装模型查询条件
            List<BusModel> modelList = busModelService.selectByPrimaryKeyWithCopy(idList);
            //循环,组装模型信息
            for (BusModel record : modelList) {
                record.setId(null); //模型id
                record.setName(record.getName() + "(复制)");//模型名称
                record.setPoststatus(0); //模型状态
                Date date = new Date();
                record.setPoststatus(0); //上线状态
                record.setOnsettime(null);
                record.setCreatetime(date); //创建时间
                record.setLastupdatetime(date);//最后更新时间
                record.setCreateuserid(this.userid);//创建人id
                record.setLastupdateuserid(this.userid);//最后更新人id
                record.setProvincecode(record.getProvincecode()); //省份信息
                record.setModelrulelist(record.getModelrulelist());
                int i = busModelService.insert(record);
            }
            return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT);
        } catch (Exception e) {
            LOGGER.error("模型复制出现异常！", e);
            return new ResultBean(ERROR_CODE_DEFAULT, "模型复制出现异常!<br>");
        }
    }


    /**
     * 复制模型，把所选模型复制到指定分类下，并自定义名称
     * <p>
     * 复制后的模型是，下线状态
     *
     * @param params 格式为json
     *               {"provinceCode":"BJ","typeId":123,"models":[{"id":123,"name":"新模型名称A"},{"id":124,"name":"新模型名称B"}]}
     * @return
     */
    @ResponseBody
    @RequestMapping("/copy/models")
    public ResultBean model_copy(
            @RequestBody Map<String, Object> params
    ) {
        LOGGER.info("模型复制为指定省份、分类下并重命名");
        try {
            String provinceCode = params.get("provinceCode").toString();
            Long typeId = Long.parseLong(params.get("typeId").toString());
            List<Map<String, Object>> models = (List<Map<String, Object>>) params.get("models");
            if (StringUtils.isEmpty(provinceCode) || null == typeId || null == models || models.size() <= 0) {
                return new ResultBean(ERROR_CODE_DEFAULT, "模型复制参数不正确!");
            }
            Map<Long, String> idNames = new HashMap<>(models.size());
            List<Long> idList = new ArrayList<>();
            for (Map<String, Object> map : models) {
                Long id = Long.parseLong(map.get("id").toString());
                idList.add(id);
                idNames.put(id, map.get("name").toString());
            }
            //组装模型查询条件
            List<BusModel> modelList = busModelService.selectByPrimaryKeyWithCopy(idList);
            //循环,组装模型信息
            for (BusModel record : modelList) {
                String newName = idNames.get(record.getId());
                record.setId(null);
                if (StringUtils.isEmpty(newName)) {
                    newName = record.getName() + "(复制)";
                }
                //模型名称
                record.setName(newName);
                //模型状态
                record.setPoststatus(0);
                //测检状态
                record.setTesttimes(0);
                Date date = new Date();
                //上线时间
                record.setOnsettime(null);
                //创建时间
                record.setCreatetime(date);
                //最后更新时间
                record.setLastupdatetime(date);
                //创建人id
                record.setCreateuserid(this.userid);
                //最后更新人id
                record.setLastupdateuserid(this.userid);
                //省份信息
                record.setProvincecode(provinceCode);
                record.setTypeid(typeId);
                record.setModelrulelist(record.getModelrulelist());
                busModelService.insert(record);
            }
            return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT);
        } catch (Exception e) {
            LOGGER.error("模型复制出现异常！", e);
            return new ResultBean(ERROR_CODE_DEFAULT, "模型复制出现异常!");
        }
    }

    /**
     * 查询指定模型
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/select/modelById/{id}")
    public ResultBean queryModelById(@PathVariable("id") Long id) {
        try {
            LOGGER.info("查询模型信息！");
            //组装模型查询条件
            BusModel model = busModelService.selectById(id);
            return new ResultBean(SUCCESS_CODE_DEFAULT, SUCCESS_MSG_DEFAULT, model);
        } catch (Exception e) {
            return resultBean;
        }
    }

    /**
     * 导出模型列表excel
     *
     * @param classify     模型分类
     * @param provincecode 省份编码
     * @param person       创建人
     * @param modelname    模型名称
     * @param keyinclude   关键字
     * @param state        模型状态
     * @param start        开始时间
     * @param end          结束时间
     * @param response     httpServletResponse
     */
    @RequestMapping("/download/modelInfo")
    public void download_model_info(
            @RequestParam(value = "classify", required = true) String classify,
            @RequestParam(value = "provincecode", required = true) String provincecode,
            @RequestParam(value = "person", required = true) String person,
            @RequestParam(value = "modelname", required = true) String modelname,
            @RequestParam(value = "keyinclude", required = false) String keyinclude,
            @RequestParam(value = "state", required = true) String state,
            @RequestParam(value = "start", required = true) Date start,
            @RequestParam(value = "end", required = true) Date end,
            HttpServletResponse response
    ) {
        LOGGER.info("导出模型列表");
        // 封装查询条件
        HashMap<String, Object> params = new HashMap<>();
        params.put("provincecode", provincecode);
        if (StringUtils.isNotEmpty(classify)) {
            params.put("typeids", formatTypeIds(Long.parseLong(classify)));
        }
        params.put("createuserid", person);
        params.put("name", modelname);
        params.put("note", keyinclude);
        params.put("poststatus", state);
        params.put("startdate", start);
        params.put("enddate", end);
        // 如果省份信息是空，且当前查询省份不是用户省份
        if (this.admin == false){
            params.put("provincecode", this.provincecode);
        }
        //组装模型查询条件
        //获取模型规则详细信息地址
        String url = PropertiesUtil.getProperty("post.model.rule");
        HSSFWorkbook wk = null;
        try {
            wk = busModelService.createExcel(params, url);
        } catch (Exception e) {
            LOGGER.error("导出模型列表异常", e);
        }
        try{
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/octet-stream");
            String filename = new String("模型列表".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xls");
            if(wk!=null){
                wk.write(out);
            }
            out.flush();
            out.close();
        }catch (Exception e) {
            LOGGER.error("导出模型列表异常", e);
        }

    }

    /**
     * 查询所有的模型（省份参数，分类参数）
     *
     * @param provincecode 省份编码
     * @param classify     分类Id多个
     * @param state        状态
     */
    @ResponseBody
    @RequestMapping("/select/all")
    public List<BusModel> query_model_condition(
            @RequestParam(value = "provincecode", required = false) String provincecode,
            @RequestParam(value = "classify", required = false) List<Integer> classify,
            @RequestParam(value = "state", required = false) Integer state
    ) {
        HashMap<String, Object> params = new HashMap<>(3);
        if (StringUtils.isEmpty(provincecode) && this.admin == false) {
            provincecode = this.provincecode;
        }
        params.put("provincecode", provincecode);
        params.put("typeids", classify);
        params.put("poststatus", state);
        return busModelService.select_model_all(params);
    }

    //查询模型分类并生成模型分类树
    private JsTreeNode buildModelTypeTree(JsTreeNode tree,String provinceCode) {
        // 初始化中国电信根节点
        tree.setId(-9999L);
        tree.setText("中国电信模型分类");
        tree.setProvincecode(null);
        //默认生成所有省份的模型分类树
        SysAreaExample areaExample = new SysAreaExample();
        if(provinceCode!=null&&provinceCode.length()>0){
            areaExample.createCriteria().andCodeEqualTo(provinceCode);
        }else if (this.admin == false) {
            //是省份人员，生成该省份模型分类树
            Long areaid = this.user.getGroup().getAreaid();
            areaExample.createCriteria().andIdEqualTo(areaid.intValue());
        }
        areaExample.setOrderByClause("id asc");

        List<SysArea> areaList = areaService.selectByExample(areaExample);
        // 存储每个省份的标签树
        List<JsTreeNode> provinceModelTypeList = new ArrayList<>();
        for (SysArea area : areaList) {
            // 循环遍历每个省份 设置省份节点 构建各省份标签树
            JsTreeNode areaNode = new JsTreeNode();
            areaNode.setId(-(long) area.getId());
            areaNode.setText(area.getArea());
            areaNode.setProvincecode(area.getCode());
            buildSingleProvinceModelTypeTree(area, areaNode);
            if (!areaNode.getChildren().isEmpty()) provinceModelTypeList.add(areaNode);
        }
        tree.setChildren(provinceModelTypeList);

        return tree;
    }

    // 获取单个省的标签 并构建树
    private void buildSingleProvinceModelTypeTree(SysArea area, JsTreeNode tree) {
        // 先获取省份code
        if (area != null) {
            tree.setText(area.getArea());
            tree.setId(0L-area.getId());
            tree.setProvincecode(area.getCode());
            // 设置每个省份的子节点
            BusModelTypeExample example = new BusModelTypeExample();
            // 先获取省份下 父节点为空的标签
            example.createCriteria()
                    .andProvincecodeEqualTo(area.getCode())
                    .andParentidIsNull();
            List<BusModelType> busModelTypeList = busModelTypeService.selectByExample(example);
            for (BusModelType modelType : busModelTypeList) {
                JsTreeNode tmp = new JsTreeNode();
                tmp.setId(modelType.getId());
                tmp.setText(modelType.getName());
                tmp.setNote(modelType.getNote());
                tmp.setProvincecode(modelType.getProvincecode());
                // 递归获取该标签下 所有字标签
                treeRecursion(modelType.getId(), tmp);
                tree.getChildren().add(tmp);
            }
        }
    }

    // 递归设置子树
    private void treeRecursion(Long id, JsTreeNode node) {
        BusModelTypeExample example = new BusModelTypeExample();
        example.createCriteria().andParentidEqualTo(id);
        List<BusModelType> groupList = busModelTypeService.selectByExample(example);
        List<JsTreeNode> children = new ArrayList<>();
        for (BusModelType modelType : groupList) {
            JsTreeNode temp = new JsTreeNode();
            temp.setId(modelType.getId());
            temp.setText(modelType.getName());
            temp.setProvincecode(modelType.getProvincecode());
            temp.setNote(modelType.getNote());
            treeRecursion(modelType.getId(), temp);
            children.add(temp);
        }
        node.setChildren(children);
    }

//    // 使用数据库装备数据构建分类树
//    private JsTreeNode buildModelTypeTreeTest(JsTreeNode tree) {
//        tree.setId(-1L);
//        tree.setText("中国电信模型分类");
//        //如果是省份人员生成一个省份分类树
//        if (this.admin == false) {
//            Long areaid = this.user.getGroup().getAreaid();
//            buildSingleProvinceModelTypeTreeTest(areaid, tree);
//            return tree;
//        }
//        //默认生成所有省份的模型分类树
//        BusModelTypeExample example = new BusModelTypeExample();
//        example.createCriteria()
//                .andParentidIsNull();
//        List<BusModelType> busModelTypes = busModelTypeService.selectByExample(example);
//        // 存储全国的分类树
//        List<JsTreeNode> jsTreeNodes = new ArrayList<>();
//        for (BusModelType record : busModelTypes) {
////            JsTreeNode jsTreeNode = new JsTreeNode(record.getId(),record.getName(),record.getNote(),null);
//            JsTreeNode backbone = new JsTreeNode();
//            buildSingleProvinceModelTypeTreeTest(Long.valueOf(record.getProvincecode()), backbone);
//            //省份主节点下没有数据,不展示
//            if (backbone.getChildren() != null && !backbone.getChildren().isEmpty()) {
//                jsTreeNodes.add(backbone);
//            }
//        }
//        tree.setChildren(jsTreeNodes);
//        //最后去除,没有子节点的省份节点
//        return tree;
//    }
//
//    //构建一个省份分类树
//    private void buildSingleProvinceModelTypeTreeTest(Long areaId, JsTreeNode tree) {
//        // 先获取省份节点
//        BusModelTypeExample example = new BusModelTypeExample();
//        example.createCriteria()
//                .andProvincecodeEqualTo(String.valueOf(areaId))
//                .andParentidIsNull();
//        // 递归获取省份下,一级节点
//        List<BusModelType> busModelTypeList = busModelTypeService.selectByExample(example);
//        for (BusModelType modelType : busModelTypeList) {
//            JsTreeNode branch = new JsTreeNode();
//            branch.setId(modelType.getId());
//            branch.setText(modelType.getName());
//            branch.setNote(modelType.getNote());
//            // 递归获取根标签下 所有子级节点
//            tree.getChildren().add(branch);
//            treeRecursionTest(modelType.getId(), branch);
//        }
//
//    }

    //    private void treeRecursionTest(Long typeId, JsTreeNode node) {
//        BusModelTypeExample example = new BusModelTypeExample();
//        example.createCriteria().andParentidEqualTo(typeId);
//        List<BusModelType> groupList = busModelTypeService.selectByExample(example);
//        List<JsTreeNode> children = new ArrayList<>();
//        for (BusModelType modelType : groupList) {
//            JsTreeNode temp = new JsTreeNode();
//            temp.setId(modelType.getId());
//            temp.setText(modelType.getName());
//            temp.setNote(modelType.getNote());
//            treeRecursionTest(modelType.getId(), temp);
//            children.add(temp);
//        }
//        node.setChildren(children);
//    }
//
    private List<Long> formatTypeIds(Long typeId) {
        List<Long> typeIds = new ArrayList<>();
        List<Long> ids_tmp = new ArrayList<>();
        ids_tmp.add(typeId);
        typeIds.add(typeId);
        while (ids_tmp.size() > 0) {
            Long idTmp = ids_tmp.remove(0);
            BusModelTypeExample example = new BusModelTypeExample();
            example.createCriteria().andParentidEqualTo(idTmp);
            List<BusModelType> list = busModelTypeService.selectByExample(example);
            for (BusModelType type : list) {
                ids_tmp.add(type.getId());
                typeIds.add(type.getId());
            }
        }
        return typeIds;
    }

}

/**
 * jstree实体类
 */
class JsTreeNode {
    // id
    private Long id;
    // 叶子显示名称
    private String text;

    private String note;

    private String provincecode;
    // 子树

    public String getProvincecode() {
        return provincecode;
    }

    public void setProvincecode(String provincecode) {
        this.provincecode = provincecode;
    }

    private List<JsTreeNode> children = new ArrayList<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public List<JsTreeNode> getChildren() {
        return children;
    }

    public void setChildren(List<JsTreeNode> children) {
        this.children = children;
    }

    public JsTreeNode() {
    }

    public JsTreeNode(Long id, String text, String note, List<JsTreeNode> children) {
        this.id = id;
        this.text = text;
        this.note = note;
        this.children = children;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("JsTreeNode{");
        sb.append("id=").append(id);
        sb.append(", text='").append(text).append('\'');
        sb.append(", note='").append(note).append('\'');
        sb.append(", children=").append(children);
        sb.append('}');
        return sb.toString();
    }

}

/**
 * 自定义类封装查询结果
 */
class ResultBean {
    private Integer code = -9999;
    private String msg = "出现异常";
    private Integer count = null;
    private Object data = null;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public ResultBean() {
    }

    public ResultBean(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResultBean(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ResultBean(Integer code, String msg, Integer count, Object data) {
        this.code = code;
        this.msg = msg;
        this.count = count;
        this.data = data;
    }

}
